<template>
  <div v-if="checkDtoInfo.id" class="approval-page">
    <!-- 左侧信息列 -->
    <div class="left-column">
      <!-- 基本信息卡片 -->
      <div class="info-card">
        <h3 class="card-title">基本信息</h3>
        <ul class="info-list">
          <li>
            <span class="label">单据编号</span>
            <span class="value">{{ checkDtoInfo.checkoutNo }}</span>
          </li>
          <li>
            <span class="label">老人姓名</span>
            <span class="value">{{ checkDtoInfo.name }}</span>
          </li>
          <li>
            <span class="label">老人身份证号</span>
            <span class="value">{{ checkDtoInfo.idCardNo }}</span>
          </li>
          <li>
            <span class="label">联系方式</span>
            <span class="value">{{ checkDtoInfo.contact }}</span>
          </li>
          <li>
            <span class="label">费用期限</span>
            <span class="value">{{ formatTime(checkDtoInfo.stayStart) }} —— {{ formatTime(checkDtoInfo.stayEnd) }}</span>
          </li>
          <li>
            <span class="label">护理等级</span>
            <span class="value">{{ checkDtoInfo.careLevel }}</span>
          </li>
          <li>
            <span class="label">入住床位</span>
            <span class="value">{{ checkDtoInfo.bedNo }}床位</span>
          </li>
          <li>
            <span class="label">签约合同</span>
            <span class="value">
              {{ checkDtoInfo.name }}的入住合同.pdf
              <a
                  v-if="checkDtoInfo.contractUrl"
                  :href="checkDtoInfo.contractUrl"
                  class="view-link"
                  target="_blank"
              >
                查看
              </a>
            </span>
          </li>
          <li>
            <span class="label">养老顾问</span>
            <span class="value">{{ checkDtoInfo.consultant || '无' }}</span>
          </li>
          <li>
            <span class="label">护理员</span>
            <span class="value">{{ checkDtoInfo.caregiverName || '无' }}</span>
          </li>
        </ul>
      </div>

      <!-- 申请信息卡片 -->
      <div class="info-card" style="margin-top: 20px;">
        <h3 class="card-title">申请信息</h3>
        <ul class="info-list">
          <li>
            <span class="label">退住日期</span>
            <span class="value">{{ checkDtoInfo.checkoutTime }}</span>
          </li>
          <li>
            <span class="label">退住原因</span>
            <span class="value">{{ checkDtoInfo.checkoutReason }}</span>
          </li>
          <li>
            <span class="label">备注</span>
            <span class="value">{{ checkDtoInfo.remark || '无' }}</span>
          </li>
          <li>
            <span class="label">申请人</span>
            <span class="value">{{ checkDtoInfo.applicant }}</span>
          </li>
          <li>
            <span class="label">申请时间</span>
            <span class="value">{{ formatTime(checkDtoInfo.applyTime, 'datetime') }}</span>
          </li>
        </ul>
      </div>

      <!-- 解除记录卡片 -->
      <div class="info-card" style="margin-top: 20px;">
        <h3 class="card-title">解除记录</h3>
        <ul class="info-list">
          <li>
            <span class="label">提交人</span>
            <span class="value">{{ checkDtoInfo.applicant }}</span>
          </li>
          <li>
            <span class="label">解除日期</span>
            <span class="value">{{ checkDtoInfo.contract ? formatTime(checkDtoInfo.contract.terminateDate) : '未设置' }}</span>
          </li>
          <li>
            <span class="label">解除协议</span>
            <span class="value">
              {{ checkDtoInfo.name }}入住合同的解除协议.pdf
              <a
                  v-if="checkDtoInfo.contract?.terminateAgreementUrl"
                  :href="checkDtoInfo.contract.terminateAgreementUrl"
                  class="view-link"
                  target="_blank"
              >
                查看
              </a>
            </span>
          </li>
        </ul>
      </div>

      <!-- 调整费用账单卡片 -->
      <div class="info-card" style="margin-top: 20px;">
        <h3 class="card-title">调整费用账单</h3>
        <div class="bill-tip">
          <i class="el-icon-info" style="color: #409eff;"></i>
          提交账单审批前，需在入账列表中处理未缴账单，若未处理，则无法提交
        </div>

        <!-- 应退区域 -->
        <div class="bill-section">
          <div class="section-header">
            <span class="section-label">应退</span>
            <span v-if="monthBill.tradeOrderNo" class="section-meta">待办：{{refundBill.good.length+1}}</span>
            <span v-if="!monthBill" class="section-meta">待办：{{refundBill.good.length+1}}</span>
            <span  class="section-meta">小计：{{total1}}元</span>
          </div>


          <div v-if="monthBill.tradeOrderNo" class="bill-item">
            <div class="item-desc">
              <span>账单编号：{{monthBill.tradeOrderNo}}</span>
              <el-button size="mini">月度账单</el-button>
            </div>
            <div class="item-desc">账单月份：{{monthBill.billMonth}}</div>
            <div class="item-desc">可退金额：{{monthBill.payableActual}}元</div>
            <!-- 实际天数（动态计算的actualDays） -->
            <div class="item-desc">实际天数：{{ monthBill.actualDays || 0 }}天</div>

            <!-- 退款天数（动态计算的unStayDays） -->
            <div class="item-desc">退款天数：{{ monthBill.unStayDays || 0 }}天</div>
            <div class="item-adjust">
              <span>实退金额：</span>
              <el-input-number v-model="refundAmount1" :min="0" :max="monthBill.payableActual"></el-input-number>
              <span>调整备注：</span>
              <el-input v-model="adjustRemark1" :maxlength="50" show-word-limit></el-input>
            </div>
          </div>
          <div class="bill-item" v-for="item in refundBill.good" >
            <div class="item-desc">
              <span>账单编号：{{item.tradeOrderNo}}</span>
              <el-button size="mini">费用账单</el-button>
            </div>
            <div class="item-desc">护理项目名称：{{item.extend1 ? item.extend1 : ""}}</div>
            <div class="item-desc">可退金额：{{item.payableAmount}}元</div>
          </div>
        </div>

        <!-- 欠费区域 -->
        <div class="bill-section" style="margin-top: 15px;">
          <div class="section-header">
            <span class="section-label">欠费</span>
            <span class="section-meta">待办：{{unPayBill.month.length}}</span>
            <span class="section-meta">小计：{{total2}}元</span>
          </div>
          <div v-for="item in unPayBill.month"  class="bill-item">
            <div class="item-desc">
              <span>账单编号：{{item.tradeOrderNo}}</span>
              <el-button size="mini">月度账单</el-button>
            </div>
            <div class="item-desc">账单月份：{{item.billMonth}}</div>
            <div class="item-desc">应付金额：{{item.payableAmount}}元</div>
          </div>

        </div>

        <!-- 余额区域 -->
        <div class="bill-section" style="margin-top: 15px;">
          <div class="section-header">
            <span class="section-label">余额</span>
            <span class="section-meta">小计：{{refundAmount2}}元</span>
          </div>
          <div class="bill-item">
            <div class="item-desc">可退押金：{{checkDtoInfo.balance?.arrearsAmount ? checkDtoInfo.balance.arrearsAmount:0}}元</div>
            <div class="item-adjust">
              <span>实退金额：</span>
              <el-input-number v-model="refundAmount2" :min="0" :max="checkDtoInfo.balance?.arrearsAmount ?checkDtoInfo.balance?.arrearsAmount:0  "></el-input-number>
              <span>调整备注：</span>
              <el-input v-model="adjustRemark2" :maxlength="50" show-word-limit></el-input>
            </div>
            <div class="item-desc">预缴费：{{ checkDtoInfo.balance?.prepaidBalance ? checkDtoInfo.balance.prepaidBalance : 0}} 元</div>
          </div>
        </div>

        <!-- 未缴区域 -->
        <div class="bill-section" v-if="unPayBill.good.length>0"  style="margin-top: 15px;">
          <div class="section-header" >
            <span class="section-label">未缴</span>
            <span class="section-meta">待办：3</span>
            <span class="section-meta">小计：60.00元</span>
          </div>
          <div class="bill-item" v-for="item in unPayBill.good">
            <div class="item-desc">
              <span>账单编号：{{ item.tradeOrderNo }}</span>
              <el-button size="mini">费用账单</el-button>
            </div>
            <div class="item-desc">护理项目名称：{{item.extend1}}</div>
            <div class="item-desc">应付金额：{{item.payableAmount}}元</div>
          </div>

        </div>

        <!-- 最终退款金额 -->
        <div class="final-amount">
          <i class="el-icon-info" style="color: #ff4d4f;"></i>
          最终退款金额 = 应退 - 欠费 + 余额 = {{total1-total2+refundAmount2+(checkDtoInfo.balance?.prepaidBalance ? checkDtoInfo.balance.prepaidBalance : 0)}}元
        </div>
      </div>
    </div>

    <!-- 右侧操作记录列 -->
    <div class="right-column">
      <!-- 操作记录卡片 -->
      <div v-if="log.activities" class="record-card">
        <h3 class="card-title">操作记录</h3>
        <ul class="record-list">
          <li v-for="item in log.activities.reverse()" class="record-item">
            <div class="item-icon">
              <!-- 替换为“发起申请”图标 -->
              <img src="@/assets/images/avatar.jpg" alt="发起申请" />
            </div>
            <div class="item-content">
              <div class="item-desc">({{ log[item.assignee]?.remark }}){{item.name}}</div>
              <div class="item-status"> {{ log[item.assignee]?.nickName }}({{item.endTime ? "已处理":"待处理"}})</div>
              <div v-if="log[item.id] " class="approval-opinion">{{log[item.id].fullMessage}}</div>
            </div>
            <div class="item-time">{{item.endTime ? formatDateStr(item.endTime):""}}</div>
          </li>

        </ul>
      </div>
    </div>

    <!-- 底部按钮 -->
    <div class="btn-area">
      <el-button type="default" @click="goBack">返回</el-button>
      <el-button v-if="isTi" type="primary" @click="submitApproval">提交</el-button>
    </div>
  </div>
</template>

<script>
import {checkOutDto, addCheckOutBill, getActivityUser, getActivityLog} from "@/api/check/checkout.js";

export default {
  name: "ApprovalPage",
  data() {
    return {
      isTi: true,
      checkDtoInfo:{},
      refundAmount1: 0, // 应退-实退金额
      adjustRemark1: "",   // 应退-调整备注
      refundAmount2: 0, // 余额-实退金额
      adjustRemark2: "",
       total1:0,
      // 余额-调整备注
      total2:0,
      total3:0,
      total4:0,
      refundBill:{
        good:[],
        month:[]
      },  //应退账单
      monthBill:{},  //当月账单
      unPayBill:{
        good:[],
        month:[]
      },// 欠费账单
      jsonData: {},
      users:{},
      log: {},
    };
  },
  methods: {
    goBack() {

      this.$router.push("/CollaborationWork/tasking"); // 路由回退
    },
    formatDateStr(dateStr) {
      // 1. 基础校验：判断是否为有效字符串且包含关键符号
      if (!dateStr || typeof dateStr !== 'string' || !dateStr.includes('T')) {
        console.warn('输入不是有效的日期格式（需包含"T"，如2025-10-23T10:42:42.000+08:00）');
        return '';
      }

      // 2. 截取核心部分：年月日（T之前） + 时分秒（T之后、.之前）
      // 例："2025-10-23T10:42:42.000+08:00" → 拆分为 ["2025-10-23", "10:42:42.000+08:00"]
      const datePart = dateStr.split('T')[0]; // 取"T"前的年月日："2025-10-23"
      const timePart = dateStr.split('T')[1].split('.')[0]; // 取"T"后、"."前的时分秒："10:42:42"

      // 3. 重组为 "年月日 时分秒" 格式
      return `${datePart} ${timePart}`;
    },
    submitApproval() {
      this.jsonData = {
        refundAmount1: this.refundAmount1,
        adjustRemark1: this.adjustRemark1,
        refundAmount2: this.refundAmount2,
        adjustRemark2: this.adjustRemark2,
        refundBill: this.refundBill,
        monthBill: this.monthBill,
        unPayBill: this.unPayBill,
        balance: this.checkDtoInfo.balance,
      };
      addCheckOutBill({
        jsonBill: JSON.stringify(this.jsonData),
        id:this.checkDtoInfo.id,
        elderId :this.checkDtoInfo.elderId
      }).then(res=>{

        console.log(res)
        this.$message.success("提交成功");
        this.$emit("next")
      })
      // 此处可添加提交账单的接口请求逻辑

    },
    formatTime(timeStr, type = "date") {
      if (!timeStr) return "-";
      const date = new Date(timeStr);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      if (type === "date") return `${year}-${month}-${day}`;

      const hour = String(date.getHours()).padStart(2, "0");
      const minute = String(date.getMinutes()).padStart(2, "0");
      const second = String(date.getSeconds()).padStart(2, "0");
      return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
    },
    getCareLevelText(level) {
      const levelMap = {
        "1": "一级护理",
        "2": "二级护理",
        "3": "三级护理",
        "4": "特级护理等级",
      };
      return levelMap[level] || level;
    },

  },
  computed: {
    total1(){
      return this.refundBill.good.reduce((total, bill) => total + bill.payableAmount, 0)+this.refundAmount1;
    },
    total2(){
      return this.unPayBill.month.reduce((total, bill) => total + bill.payableAmount, 0);
    },
    total3(){
      // return this.checkDtoInfo.balance.
    },
    total4(){
      return this.refundBill.good.reduce((total, bill) => total + bill.payableAmount, 0);
    },


  },
  mounted() {
    checkOutDto(this.id).then(res => {

      this.checkDtoInfo = res.data;
      if(this.checkDtoInfo.processStatus>=4){
        this.isTi = false;
      }
      const checkoutDate = new Date(this.checkDtoInfo.checkoutTime);
      res.data.bills.forEach(bill => {
        const billEndDate = bill.billEndTime ? new Date(bill.billEndTime) : null;
        const billStartDate = bill.billStartTime ? new Date(bill.billStartTime) : null;
        if(bill.billType === "1"){
          if(billEndDate>checkoutDate && bill.billStatus === "1"){
            this.refundBill.good.push(bill);
          }else if(billEndDate<checkoutDate && bill.billStatus === "0"){
            this.unPayBill.good.push(bill);
          }
        }else{
          if(billStartDate>checkoutDate && bill.billStatus === "1"){
            this.refundBill.month.push(bill);
          }else if(billEndDate<checkoutDate && bill.billStatus === "0"){
            this.unPayBill.month.push(bill);
          }else if(bill.billStatus==="1" && billEndDate>checkoutDate ){
            console.log(bill);
            console.log(checkoutDate+"  " + billStartDate + "  " + billEndDate);
            // 1. 计算实际居住天数和未居住天数
            const actualTimeDiff = checkoutDate - billStartDate;
            const actualDays = Math.floor(actualTimeDiff / (1000 * 60 * 60 * 24));

            const unStayTimeDiff = billEndDate - checkoutDate;
            const unStayDays = Math.floor(unStayTimeDiff / (1000 * 60 * 60 * 24)) - 1; // 按需求减1
            console.log(actualDays, unStayDays);
            // 2. 计算应付金额（核心）
            // 总金额（payableAmount）、总天数（totalDays）从账单取，需转换为数字
            const totalAmount = Number(bill.payableAmount) || 0;
            const totalDays = Number(bill.totalDays) || 0;

            // 避免除以0（总天数为0时默认每天费用为0）
            const dailyRate = totalDays > 0 ? totalAmount / totalDays : 0;

            // 应付金额 = 实际居住天数 × 每天费用（保留2位小数）
            const payableActual = Number(((actualDays+1 )* dailyRate).toFixed(2));

            // 3. 给账单添加计算结果
            bill.actualDays = actualDays; // 实际居住天数
            bill.unStayDays = unStayDays; // 未居住天数
            bill.dailyRate = dailyRate.toFixed(2); // 每天费用（元）
            bill.payableActual = bill.payableAmount-payableActual; // 应付金额（元）



            // 存入monthBill数组
            this.monthBill= bill;
            this.refundAmount2=this.checkDtoInfo.balance?.arrearsAmount ? this.checkDtoInfo.balance?.arrearsAmount:0
            this.refundAmount1=this.monthBill.payableActual
          }

        }
      });

      console.log(this.unPayBill.month);
      console.log(this.refundBill.good);
    });

    getActivityLog(this.id).then(res=>{
      this.log = res.data
      this.log.activities=res.data.activities.reverse()
    })



  },
  props: {
    id: {
      type: [Number,String],
      default: 0,
    },
  },


};

</script>

<style scoped>
.approval-page {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  padding: 20px;
}

.left-column {
  width: 60%;
}

.right-column {
  width: 38%;
}

.info-card,
.record-card {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 20px;
  margin-bottom: 20px;
}

.card-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 20px;
}

.info-list {
  list-style: none;
  padding: 0;
}

/* 标签右对齐样式 */
.info-list li {
  display: flex;
  margin-bottom: 15px;
}

.info-list .label {
  width: 120px;
  text-align: right;
  margin-right: 15px;
  color: #606266;
}

.info-list .value {
  flex: 1;
}

.view-link {
  color: #409eff;
  text-decoration: none;
  margin-left: 5px;
}

/* 账单提示样式 */
.bill-tip {
  display: flex;
  align-items: center;
  background-color: #f5f7fa;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 8px;
  margin-bottom: 15px;
}

/* 账单区域样式 */
.bill-section {
  border: 1px dashed #ebeef5;
  padding: 15px;
  border-radius: 4px;
}

.section-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.section-label {
  font-weight: bold;
  margin-right: 10px;
}

.section-meta {
  color: #909399;
  font-size: 12px;
  margin-right: 10px;
}

.bill-item {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 10px;
  margin-bottom: 10px;
}

.item-desc {
  margin-bottom: 5px;
}

.item-adjust {
  display: flex;
  align-items: center;
  margin-top: 5px;
}

.item-adjust span {
  margin-right: 5px;
}

.el-input-number {
  width: 120px;
  margin-right: 10px;
}

.el-input {
  width: 200px;
}

/* 最终金额提示 */
.final-amount {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 15px;
  color: #ff4d4f;
}

/* 操作记录核心样式（流程线 + 布局） */
.record-list {
  list-style: none;
  padding: 0;
  position: relative; /* 作为伪元素的定位容器 */
}

.record-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 30px;
}

/* 垂直主线：连接所有记录项（除第一个），从头像中间穿过 */
.record-item:not(:first-child)::before {
  content: '';
  position: absolute;
  left: 20px; /* 与40px宽图标中心对齐（40/2=20） */
  top: 41px;
  height: 30px;
  width: 2px;
  background-color: #dcdcdc; /* 浅灰色流程线 */
}

.item-icon {
  margin-right: 12px;
}

.item-icon img {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
}

.item-content {
  flex: 1;
}

.item-desc {
  font-weight: 500;
}

.item-status {
  color: #909399;
  font-size: 12px;
}

/* 审批意见提示框 */
.approval-opinion {
  background-color: #f5f7fa;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 10px;
  margin-top: 5px;
  font-size: 12px;
  color: #606266;
}

.item-time {
  color: #909399;
  font-size: 12px;
  white-space: nowrap; /* 防止时间换行 */
}

/* 底部按钮 */
.btn-area {
  margin-top: 40px;
  text-align: center;
  width: 100%;
}

.btn-area button {
  margin: 0 10px;
}
</style>